﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GorgonLibrary.Graphics;
using GorgonLibrary;
using System.Diagnostics;

namespace EngineOfEvermore.Editor.Common
{
    public class GorgonRenderTargetManager
    {
        class RenderTargetListEntry
        {
            public RenderTargetListEntry( RenderTarget renderTarget, 
                Action<FrameEventArgs> renderAction )
            {
                this.RenderTarget = renderTarget;
                this.RenderAction = renderAction;
            }

            public readonly RenderTarget RenderTarget;
            public readonly Action<FrameEventArgs> RenderAction;
        }

        List<RenderTargetListEntry> _renderTargetList = new List<RenderTargetListEntry>();

        public GorgonRenderTargetManager()
        {
            Gorgon.Idle += new FrameEventHandler( _gorgonIdle );
        }

        public void Add( RenderTarget target, Action<FrameEventArgs> renderAction )
        {
            if ( !_renderTargetList.Any( x => x.RenderTarget == target ) )
            {
                _renderTargetList.Add( new RenderTargetListEntry( target, renderAction ) );
            }
        }

        public void Remove( RenderTarget target )
        {
            Debug.Assert( _renderTargetList.Count( x => x.RenderTarget == target ) <= 1 );

            _renderTargetList.RemoveAll( x => x.RenderTarget == target );
        }

        void _gorgonIdle( object sender, FrameEventArgs e )
        {
            foreach ( RenderTargetListEntry entry in _renderTargetList )
            {
                entry.RenderAction( e );
            }
        }
    }
}
